package cn.yunhe.insurance.controller;


import cn.yunhe.insurance.entity.Branch;
import cn.yunhe.insurance.entity.Emp;
import cn.yunhe.insurance.entity.Role;
import cn.yunhe.insurance.service.EmpService;
import cn.yunhe.insurance.service.RoleService;
import cn.yunhe.insurance.service.impl.BranchService;
import cn.yunhe.insurance.util.FileUploadUtil;
import cn.yunhe.insurance.util.PhoneCodeUtil;
import cn.yunhe.insurance.util.Result;
import cn.yunhe.insurance.util.UUIDGenerator;
import cn.yunhe.insurance.webSocket.MyWebSocket;
import com.github.pagehelper.Page;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @program: ssm_insurance
 * @description: 员工管理控制器(Controller层)
 * @author: 李武
 * @create: 2018-09-15 10:29
 **/
@Controller
@RequestMapping("/emp")
public class EmpController {
    @Resource
    private EmpService empService;
    @Resource
    private BranchService branchService;
    @Resource
    private RoleService roleService;
    //登录次数验证标志
    private int flag = 0;

    @RequestMapping("/toUpdatePic")
    public ModelAndView toUpdatePic(HttpSession session) {
        Emp emp= (Emp) session.getAttribute("emp");
        Emp emp1 = empService.getOneEmp(emp);
        ModelAndView modelAndView=new ModelAndView("updatePic");
        modelAndView.addObject("emp1",emp1);
        return  modelAndView;
    }


    /**
     * 修改头像
     * @param file
     * @param session
     * @return
     */
    @RequestMapping(value = "/addOrUpdatePic", method = RequestMethod.POST)
    public ModelAndView addCars(@RequestParam MultipartFile file, HttpSession session, String oldPicName) {
        String filePath = "/usr/uploadFiles";
        if (oldPicName != null || oldPicName != "") {
            File oldPic=new File(filePath+File.separator+oldPicName);
            oldPic.delete();
        }
        String fileName = FileUploadUtil.fileUpLoad(file);
        /*从session中获取euuId*/
        Emp emp1 = (Emp) session.getAttribute("emp");
        emp1.setEuuId(emp1.getEuuId());
        emp1.setPic(fileName);
        empService.addOrUpdatePic(emp1);
        ModelAndView mv = new ModelAndView();
        mv.setView(new MappingJackson2JsonView());
        return mv;
    }

    /*自我修改*/
    @RequestMapping("/toUpEmpPs")
    public @ResponseBody
    Result updateEmpPassword(Emp emp) {
        /*密码加盐*/
        String password1 = emp.getEmpPassword();
        String password = new SimpleHash("MD5", password1, ByteSource.Util.bytes(emp.getEmpName()), 1024).toString();
        emp.setEmpPassword(password);
        empService.updateEmpPassword(emp);
        return new Result();
    }

    @RequestMapping("/toUpdateEmpPWTable")
    public ModelAndView toUpdateEmpPWTable() {
        return new ModelAndView("updateEmpPassword");
    }

    @RequestMapping("/toGetEmpTable")
    public ModelAndView toGetEmpTable() {
        return new ModelAndView("getEmp");
    }

    @RequestMapping("/toAddEmpTable")
    public ModelAndView toAddEmpTable() {
        return new ModelAndView("addEmp");
    }

    /*跳转updateEmp.ftl页面控制器*/
    @RequestMapping("/toUpdateEmpTable")
    public ModelAndView toUpdateEmpTable(Emp emp) {
        Emp emp1 = empService.getOneEmp(emp);
        ModelAndView mv = new ModelAndView("updateEmp");
        mv.addObject("emp1", emp1);
        return mv;
    }

    @RequestMapping("/doGetBranchList")
    public ModelAndView getBranchList() {
        List<Branch> branchList = branchService.findAllBranch();
        //System.out.println("支点数:" + branchList.size());
        ModelAndView mv = new ModelAndView();
        mv.setView(new MappingJackson2JsonView());
        mv.addObject("branchList", branchList);
        return mv;

    }

    @RequestMapping("/getAllRole")
    public ModelAndView getAllRole() {
        List<Role> roleList = roleService.getAllRole();
        //System.out.println("角色数:" + roleList.size());
        ModelAndView mv = new ModelAndView();
        mv.setView(new MappingJackson2JsonView());
        mv.addObject("roleList", roleList);
        return mv;
    }

    @RequestMapping("/toAddEmp")
    public ModelAndView toAddEmp(Emp emp, Role role, Branch branch) {
        Map<String, Object> map = new HashMap<String, Object>();
        /*获取UUId*/
        emp.setEuuId(UUIDGenerator.getUUID());
        /*添加状态.0:存在,1:删除*/
        emp.setEmpState(0);
        /*密码加盐*/
        String password1 = emp.getEmpPassword();
        String password = new SimpleHash("MD5", password1, ByteSource.Util.bytes(emp.getEmpName()), 1024).toString();
        emp.setEmpPassword(password);
        /*登录状态*/
        emp.setLoginState(0);
        /*0:账号正常*/
        emp.setAccountState(0);
        map.put("emp", emp);
        map.put("role", role);
        map.put("branch", branch);
        empService.addEmp(map);
        return new ModelAndView("getEmp");
    }

    @RequestMapping("/toDelEmp")
    public @ResponseBody
    Result delEmp(Emp emp) {
        empService.delEmp(emp);
        return new Result();
    }

    /*批量删除员工信息的控制器*/
    @RequestMapping("/toDelsEmp")
    public ModelAndView delsEmp(@RequestParam(value = "euuIdList[]") String[] euuIdList) {
        List<String> euuId = Arrays.asList(euuIdList);
        empService.delsEmp(euuId);
        return new ModelAndView("getEmp");
    }

    /*修改员工的控制器*/
    @RequestMapping("/toUpdateEmp")
    public @ResponseBody
    Result updateEmp(Emp emp, Role role, Branch branch) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("emp", emp);
        map.put("role", role);
        map.put("branch", branch);
        empService.updateEmp(map);
        return new Result();
    }

    @RequestMapping("/toGetEmpByPage")
    public ModelAndView getEmpByPage(int pageSize, int pageNum, String keyword, Branch branch, Role role) {
        Map map = new HashMap();
        map.put("pageSize", pageSize);//每页显示的条数
        map.put("pageNum", pageNum);//当前页码
        map.put("keyword", keyword);//模糊搜索
        map.put("branch", branch);//支点对象
        map.put("role", role);//角色对象
        Page page = empService.getEmpListById(map);
        ModelAndView mv = new ModelAndView();
        mv.setView(new MappingJackson2JsonView());
        mv.addObject("page", page);//查询的结果集
        mv.addObject("totalPage", page.getPages());//总页数
        mv.addObject("total", page.getTotal());//总条数
        //System.out.println("总页数:" + page.getPages());
        return mv;
    }
    /*======================================================================*/

    /**
     * 登录操作
     *
     * @param emp
     * @param session
     * @return
     */
    @RequestMapping("/login")

    public String login(Emp emp, HttpSession session) {
        String result = null;
        Subject currUser = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(emp.getEmpName(), emp.getEmpPassword());
        try {
            currUser.login(token);

            emp.setLoginState(1);

            Emp emp1 = (Emp) currUser.getPrincipal();

            if (emp1.getLoginState() == 1) {
                try {
                    MyWebSocket.sendInfo("101");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            boolean flag = empService.updateLoginState(emp);//更改数据库登录状态

            if (!flag) {
                //增加日志输出信息
            }
            emp1.setLoginState(1);//更改session中登录状态
            session.setAttribute("emp", emp1);

            // model.addAttribute("emp", emp1);
            result = "redirect:/emp/index";

            //token.setRememberMe(true); //remember me 操作
        } catch (AuthenticationException ae) {
            System.out.println(ae.getMessage());
            if (session.getAttribute(emp.getEmpName()) != null &&
                    session.getAttribute(emp.getEmpName()).equals("101")) {
                flag++;
            } else {
                session.setAttribute(emp.getEmpName(), "101");
                flag++;
            }
            if (flag == 3) {
                emp.setAccountState(1);//更改账户状态
                boolean flg = empService.updateAccountState(emp);//冻结账户状态
                if (flg) {
                    MyThread mythread = new MyThread();
                    mythread.setEmp(emp);
                    Thread thread = new Thread(mythread);
                    thread.start();
                }
            }
            result = "redirect:/login.html";
        }
        return result;
    }

    @RequestMapping("/index")
    public ModelAndView index() {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("index");
        return mv;
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        Emp emp = (Emp) session.getAttribute("emp");
        emp.setLoginState(0);
        boolean flag = empService.updateLoginState(emp);
        Subject currentEmp = SecurityUtils.getSubject();
        currentEmp.logout();
        if (!flag) {
            //错误信息操作
            return "redirect:/404.html";
        }

        return "redirect:/login.html";
    }

    @RequestMapping("/getInfo")
    public ModelAndView get(Emp emp) {
        emp = empService.getEmpByName(emp);
        ModelAndView mv = new ModelAndView();
        mv.setView(new MappingJackson2JsonView());
        mv.addObject("emp", emp);
        return mv;
    }
    @RequestMapping("/verifyCode")
    public ModelAndView verifyCode(String verifyCode,HttpSession session){
        ModelAndView mv=new ModelAndView();
        mv.setView(new MappingJackson2JsonView());

        String very= (String) session.getAttribute("veryCode");
       // String very="123";

        if(very.equals(verifyCode)){
            mv.addObject("info","验证成功");
        }else{
            mv.addObject("info","验证失败");
        }
        return mv;
    }

    @RequestMapping("/getVeryCode")
    public ModelAndView getVeryCode(Emp emp,HttpSession session) {
        String veryCode = PhoneCodeUtil.getPhoneVeryCode(emp.getEmpPhone());
        session.setAttribute("veryCode",veryCode);
        ModelAndView mv = new ModelAndView();
        mv.setView(new MappingJackson2JsonView());
        mv.addObject("veryCode", veryCode);
        return mv;

    }

    @RequestMapping("/updatePassword")
    public String updatePassword(Emp emp) {
       if(emp.getEmpPassword()!=null&&emp.getEmpName()!=null ){
           String password = new SimpleHash("MD5", emp.getEmpPassword(),
                   ByteSource.Util.bytes(emp.getEmpName()), 1024).toString();
           emp.setEmpPassword(password);
           boolean flag = empService.updatePassword(emp);
           if (flag) {
               return "redirect:/login.html";
           }
       }
        return "redirect:/404.html";
    }

    //创建线程操作
    class MyThread implements Runnable {
        private Emp emp;

        public Emp getEmp() {
            return emp;
        }

        public void setEmp(Emp emp) {
            this.emp = emp;
        }

        @Override
        public void run() {
            emp.setAccountState(0);
            int i = 60;
            while (i > 0) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                i--;
            }
            boolean flag = empService.updateAccountState(emp);
            if (flag) {
                //账户解冻
            }
        }
    }


    public EmpService getEmpService() {
        return empService;
    }

    public void setEmpService(EmpService empService) {
        this.empService = empService;
    }

    public BranchService getBranchService() {
        return branchService;
    }

    public void setBranchService(BranchService branchService) {
        this.branchService = branchService;
    }

    public RoleService getRoleService() {
        return roleService;
    }

    public void setRoleService(RoleService roleService) {
        this.roleService = roleService;
    }
}
